﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZGRemote.Server.UI.Resources;

namespace ZGRemote.Server.UI.ViewModels
{
    public partial class SettingsViewModel : ViewModelBase
    {
        [ObservableProperty]
        private Array languages;

        [ObservableProperty]
        private LanguageEnum currentLanguage;

        [ObservableProperty]
        private int listenPort;

        [ObservableProperty]
        private bool autoListen;

        [ObservableProperty]
        private bool serverListening;

        public SettingsViewModel()
        { 
            header = Core.Properties.Resources.Settings;
            languages = Enum.GetValues(typeof(LanguageEnum));
            currentLanguage = ResourceService.Current.GetCurrentLanguage();
            listenPort = SettingConfig.Settings.ListenPort;
            autoListen = SettingConfig.Settings.AutoListen;
            serverListening = autoListen;
        }

        [RelayCommand]
        private void LanguageChanged()
        {
            ResourceService.Current.ChangedCulture(CurrentLanguage);
        }

        partial void OnListenPortChanged(int oldValue, int newValue)
        {
            if (oldValue != newValue)
            {
                SettingConfig.Settings.ListenPort = newValue;
                SettingConfig.Settings.Save();
            }
        }

        partial void OnAutoListenChanged(bool oldValue, bool newValue)
        {
            if (oldValue != newValue)
            {
                SettingConfig.Settings.AutoListen = newValue;
                SettingConfig.Settings.Save();
            }
        }

        partial void OnServerListeningChanged(bool value)
        {
            if (value)
            {
                if (App.Current.Server.IsRunning) return;
                App.Current.Server.Start(SettingConfig.Settings.ListenIP, SettingConfig.Settings.ListenPort);
                Growl.Success(Core.Properties.Resources.ServerStart);
            }
            else
            {
                if (!App.Current.Server.IsRunning) return;
                App.Current.Server.Stop();
                Growl.Success(Core.Properties.Resources.ServerStop);
            }
        }
    }
}
